package com.mrzhou.file.util;

import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

import java.io.*;
import java.nio.charset.Charset;

/**
 * 生成pdf文件
 */
public class PdfUtil {

    public  static String htmlToPdf(String html)  {
        Document doc = new Document(PageSize.LETTER);
        File file;
        try{
            file = File.createTempFile("temp", ".pdf");
            PdfWriter pdfWriter = PdfWriter.getInstance(doc, new FileOutputStream(file));
            doc.open();
            XMLWorkerHelper helper = XMLWorkerHelper.getInstance();
            helper.parseXHtml(pdfWriter, doc, new ByteArrayInputStream(html.getBytes(Charset.forName("UTF-8"))), Charset.forName("UTF-8"), new DefineFontProvider());
            doc.close();
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String handlerHtmlTemplate(String[] args, String classpath) {
        InputStream is;
        InputStreamReader isr;
        BufferedReader bf = null;
        try {
            is = PdfUtil.class.getClassLoader().getResourceAsStream(classpath);
            isr = new InputStreamReader(is, "UTF-8");
            bf = new BufferedReader(isr);

            int index = 0;
            StringBuffer sb = new StringBuffer();
            String t;
            while ( (t = bf.readLine()) != null) {
                String i = "${"+ index +"}";
                while(t.indexOf(i) != -1) {
                    if(index < args.length) {
                        t = t.replace(i, args[index]);
                    }
                    index++;
                    i = "${"+ index +"}";
                }
                sb.append(t);
            }
            return sb.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(bf != null) {
                try {
                    bf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
/*

    public static void main(String[] args) {
        try {
            Long startTime = System.currentTimeMillis();
            String[] param = {"张康康", "15332652546", "机构采购系统", "VCN0024259", "机构采购系统", "张康康", "隆冬寒梅", "呵呵呵大哒", "呵呵呵大哒", "2020-07-20", "2020-07-20"};
            String path = PdfUtil.htmlToPdf(PdfUtil.handlerHtmlTemplate(param, "template/auth.html"));
            System.out.printf("程序运行时间: %dms\n生成的文件地址: %s\n", (System.currentTimeMillis() - startTime), path);
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
*/
}
